# coding: utf8
# datetime: 2021-03-16
# 题目地址: https://leetcode-cn.com/problems/spiral-matrix-ii/


from typing import List


class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        ret_matrix = [[0]*n for _ in range(n)]

        left, top, right, bottom = 0, 0, n-1, n-1
        num = 1
        max_num = n*n+1
        while num<max_num:
            if left == bottom:
                ret_matrix[top][left] = num
                break
            # 左到右
            for i in range(left, right):
                ret_matrix[top][i] = num
                num += 1
            # 上到下
            for i in range(top, bottom):
                ret_matrix[i][right] = num
                num += 1
            # 右到左
            for i in range(right, left, -1):
                ret_matrix[bottom][i] = num
                num += 1
            # 下到上
            for i in range(bottom, top, -1):
                ret_matrix[i][left] = num
                num += 1
            left, top, right, bottom = left+1, top+1, right-1, bottom-1
        return ret_matrix


a = Solution()
print(a.generateMatrix(2))
